package com.witdata.common.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.mysql.base.service.VersionBaseService;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.VersionDto;
import com.witdata.mysql.domain.entity.TVersion;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.VersionMapper;
import com.witdata.common.service.FileService;
import com.witdata.common.service.VersionService;
import com.witdata.common.util.IdUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class VersionServiceImpl implements VersionService {
    private final VersionBaseService versionBaseService;
    private final FileService fileService;

    @Override
    public boolean check(String version) {
        log.info("now => {}", version);
        TVersion tVersion = versionBaseService.getOne(new QueryWrapper().orderBy("upload_time", false));
        log.info("tVersion => {}", tVersion);
        return compareVersion(version, tVersion.getName());
    }

    @Transactional
    @Override
    public void upload(MultipartFile file, String name, String content) {
        System.out.println("file = " + file.getOriginalFilename());
        String url = "/version/" + name;
        url = fileService.uploadFile(file, url);
        boolean save = versionBaseService.save(TVersion.builder()
                .id(IdUtils.createId())
                .name(name)
                .url(url)
                .content(content)
                .uploadTime(LocalDateTime.now())
                .build());
        if (!save) throw new GlobalException(Status.UPLOADERROR);
    }

    @Override
    public List<VersionDto> getVersionList() {
        List<TVersion> tVersionList = versionBaseService.list();
        return VersionMapper.INSTANCE.toVersionDtoList(tVersionList);
    }

    @Override
    public VersionDto getLatestVersion() {
        TVersion tVersion = versionBaseService.getOne(new QueryWrapper().orderBy("upload_time", false));
        return VersionMapper.INSTANCE.toVersionDto(tVersion);
    }

    public boolean compareVersion(String currentVersion, String newVersion) {
        String[] currentSplit = currentVersion.split("\\.");
        String[] newSplit = newVersion.split("\\.");
        if (currentSplit.length != newSplit.length) return true;
        for (int i = 0; i < currentSplit.length; i++) {
            if (newSplit[i].compareTo(currentSplit[i]) > 0) return true;
        }
        return false;
    }
}
